package view;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.BlogDao;
import dao.User;
import session.Session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/blogList")
public class BlogList extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = Session.isLogin(req);
        if (user == null){
            String get = req.getHeader("Referer");
            if (get == null){
                resp.sendRedirect("login.html");
                return;
            }
            resp.setStatus(403);
            return;
        }
        resp.setContentType("application/json;charset=utf-8");
        BlogDao blogDao = new BlogDao();
        String blogId = req.getParameter("blogId");
        if (blogId == null){
            List<Blog> list = new ArrayList<>();
            try {
                list = blogDao.selectAll();
                String jsonString = objectMapper.writeValueAsString(list);
                System.out.println(jsonString);
                resp.getWriter().write(jsonString);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else {
            try {
                Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
                String jsonString = objectMapper.writeValueAsString(blog);
                resp.getWriter().write(jsonString);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
